/**
 * 
 */
package web;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import model.IAlbum;
import model.IArtist;
import model.ISong;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.validation.BindException;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;

import session.UserContainer;

import bus.AlbumManagement;
import dao.IAlbumDAO;
import dao.IArtistDAO;
import dao.ISongDAO;
import filesystem.MusicFinder;

/**
 * @spring.bean id="albumManagementForm"
 * @spring.property name="sessionForm" value="true"
 * @spring.property name="commandName" value="albumManagement"
 * @spring.property name="validator" ref="albumManagementValidator"
 * @spring.property name="formView" value="auth/albumManagement"
 * 
 * @spring.property name="albumService" ref="ALBUM_SERVICE"
 * @spring.property name="artistService" ref="ARTIST_SERVICE"
 * @spring.property name="songService" ref="SONG_SERVICE"
 * 
 * @author ipeel
 *
 */
public class AlbumManagementFormController extends SimpleFormController {
	protected final Log logger = LogFactory.getLog(getClass());
	private IAlbumDAO albumService;
	private IArtistDAO artistService;
	private ISongDAO songService;
	
	public ModelAndView onSubmit(
			HttpServletRequest request, 
			HttpServletResponse response, 
			Object command, 
			BindException errors) throws Exception {
		HttpSession session = request.getSession();
		UserContainer uc = (UserContainer)session.getAttribute(IConstants.Sessoin.USER_CONTAINER);
		
		//Search in progress.
		if(uc.getMusic() != null) {
			Map<String, Object> beans = new HashMap<String, Object>();
			beans.put("searchInProgress", true);
			beans.put("searchPath", uc.getMusic().getSearchPath());
			return showForm(request, response, errors, beans);
		}
		uc.setMusic(new MusicFinder());
		
		AlbumManagement albumManagementForm = (AlbumManagement)command;
		uc.getMusic().setSearchPath(albumManagementForm.getPath());
		uc.getMusic().parseFiles(albumManagementForm.getPath());

		List<IArtist> artists = new ArrayList<IArtist>();
		for(String artistName: uc.getMusic().getArtists().keySet()) {
			artists.add(uc.getMusic().getArtists().get(artistName));
		}
		
		//Save all the albums.
		for(IArtist artist: artists) {
			IArtist existingArtist = getArtistService().getArtistByName(artist.getName());
			
			if(existingArtist == null) {
				getArtistService().saveArtist(artist);
			} else {
				for(IAlbum album: artist.getAlbums()) {
					IAlbum existingAlbum = getAlbumService().getAlbumByName(album.getName());
					
					if(existingAlbum == null) {
						existingArtist.getAlbums().add(album);
					} else {
						for(ISong song: existingAlbum.getSongs()) {
							ISong existingSong = getSongService().getSongByNameInAlbum(song.getName(), existingAlbum);
							
							if(existingSong == null) {
								album.addSong(song);
							}
						}
					}
				}
				
				getArtistService().saveArtist(existingArtist);
			}
		}
		
		Map<String, Object> beans = new HashMap<String, Object>();
		beans.put("artists", artists);
		beans.put("invalidSongs", uc.getMusic().getInvalidSongs());
		
		uc.setMusic(null);
		
		return new ModelAndView(IConstants.Views.MUSIC_SEARCH_STATUS, beans);
	}
	
	/* (non-Javadoc)
	 * @see org.springframework.web.servlet.mvc.AbstractFormController#handleRequestInternal(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
	 */
	@Override
	protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) throws Exception {
		HttpSession session = request.getSession();
		UserContainer uc = (UserContainer)session.getAttribute(IConstants.Sessoin.USER_CONTAINER);
		
		Map<String, Object> beans = new HashMap<String, Object>();
		//Search in progress.
		if(uc.getMusic() != null) {
			beans.put("searchInProgress", true);
			beans.put("searchPath", uc.getMusic().getSearchPath());
		} else {
			beans.put("searchInProgress", false);
		}		
		
		ModelAndView formView = super.handleRequestInternal(request, response);
		formView.addAllObjects(beans);
		return formView;
	}

	protected Object formBackingObject(HttpServletRequest request) throws ServletException {
		return new AlbumManagement();
	}

	/**
	 * @return Returns the albumService.
	 */
	public IAlbumDAO getAlbumService() {
		return albumService;
	}

	/**
	 * @param personService The albumService to set.
	 */
	public void setAlbumService(IAlbumDAO personService) {
		this.albumService = personService;
	}

	/**
	 * @return Returns the artistService.
	 */
	public IArtistDAO getArtistService() {
		return artistService;
	}

	/**
	 * @param artistService The artistService to set.
	 */
	public void setArtistService(IArtistDAO artistService) {
		this.artistService = artistService;
	}

	/**
	 * @return Returns the songService.
	 */
	public ISongDAO getSongService() {
		return songService;
	}

	/**
	 * @param songService The songService to set.
	 */
	public void setSongService(ISongDAO songService) {
		this.songService = songService;
	}
}